<script lang="ts" setup>
import {computed, onMounted, reactive, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {DeleteOutlined, DownloadOutlined, EditOutlined, EyeOutlined, ShareAltOutlined} from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import MainLayout from '@/components/layout/MainLayout.vue'
import ProgressiveImage from '@/components/common/ProgressiveImage.vue'
import {pictureApi, spaceApi} from '@/api'
import {useAuthStore} from '@/stores/modules/auth'
import type {PictureUpdateDTO} from '@/types/dto/picture'
import type {PictureVO} from '@/types/vo/picture'
import type {SpaceVO} from '@/types/vo/space'
import {formatFileSize} from '@/utils/format'
import {getCategoryLabel, getReviewStatusColor, getReviewStatusText, PICTURE_CATEGORIES} from '@/constants/picture'
import {error, handleError, success} from '@/utils/message'
import {PICTURE} from '@/constants/messages'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

const loading = ref(false)
const updating = ref(false)
const editModalVisible = ref(false)
const picture = ref<PictureVO | null>(null)
const mySpaces = ref<SpaceVO[]>([])

const editForm = reactive<PictureUpdateDTO>({
  pictureName: '',
  introduction: '',
  category: '',
  tags: [],
  spaceId: undefined
})

// 是否可以编辑
const canEdit = computed(() => {
  return authStore.user && picture.value &&
      (authStore.user.id === picture.value.userId || authStore.user.userRole === 'admin')
})

// 加载图片详情
const loadPicture = async () => {
  const id = Number(route.params.id)
  if (!id || isNaN(id)) {
    error('图片ID无效')
    router.push('/explore')
    return
  }

  loading.value = true
  try {
    picture.value = await pictureApi.getById(id)
  } catch (error: any) {
    handleError(error, PICTURE.LOAD_FAILED)
    router.push('/explore')
  } finally {
    loading.value = false
  }
}

// 下载图片
const handleDownload = () => {
  if (!picture.value) return

  // 使用隐藏的 <a> 标签下载，避免浏览器拦截
  const url = `/api/picture/${picture.value.id}/download`
  const link = document.createElement('a')
  link.href = url
  link.download = `${picture.value.pictureName}.${picture.value.picFormat}` || 'image'
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)

  success(PICTURE.DOWNLOAD_START)
}

// 分享图片 - 复制详情页面链接
const handleShare = async () => {
  if (!picture.value) return

  try {
    // 生成详情页面链接
    const shareUrl = `${window.location.origin}/picture/${picture.value.id}`

    // 调用后端接口增加分享次数
    await pictureApi.share(picture.value.id!)

    // 复制详情页链接到剪贴板
    await navigator.clipboard.writeText(shareUrl)
    success(PICTURE.SHARE_SUCCESS)
  } catch (error: any) {
    handleError(error, PICTURE.SHARE_FAILED)
  }
}

// 加载我的空间列表
const loadMySpaces = async () => {
  try {
    const result = await spaceApi.getMySpaces()
    mySpaces.value = [...result.owner, ...result.joined]
  } catch (error: any) {
    // 静默失败，不影响主流程
  }
}

// 显示编辑对话框
const showEditModal = async () => {
  if (!picture.value) return

  // 加载空间列表
  await loadMySpaces()

  editForm.pictureName = picture.value.pictureName
  editForm.introduction = picture.value.introduction
  editForm.category = picture.value.category
  editForm.tags = picture.value.tags || []
  editForm.spaceId = picture.value.spaceId
  editModalVisible.value = true
}

// 更新图片信息
const handleUpdate = async () => {
  if (!picture.value) return

  updating.value = true
  try {
    const result = await pictureApi.update(picture.value.id!, editForm)
    picture.value = result
    editModalVisible.value = false
    success(PICTURE.UPDATE_SUCCESS)
  } catch (error: any) {
    handleError(error, PICTURE.UPDATE_FAILED)
  } finally {
    updating.value = false
  }
}

// 删除图片
const handleDelete = async () => {
  if (!picture.value) return

  try {
    await pictureApi.delete(picture.value.id!)
    success(PICTURE.DELETE_SUCCESS)
    router.push('/explore')
  } catch (error: any) {
    handleError(error, PICTURE.DELETE_FAILED)
  }
}

// 格式化日期
const formatDate = (date?: string) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm') : ''
}

onMounted(() => {
  loadPicture()
})
</script>

<template>
  <main-layout>
    <div class="picture-detail-container">
      <a-spin :spinning="loading">
        <div v-if="picture" class="detail-content">
          <!-- 图片展示区 -->
          <div class="image-section">
            <div class="image-wrapper">
              <progressive-image
                  :alt="picture.pictureName"
                  :lazy="false"
                  :src="picture.fileUrl"
              />
            </div>

            <!-- 操作按钮 -->
            <div class="image-actions">
              <a-space>
                <a-button type="primary" @click="handleDownload">
                  <template #icon>
                    <DownloadOutlined/>
                  </template>
                  下载
                </a-button>
                <a-button @click="handleShare">
                  <template #icon>
                    <ShareAltOutlined/>
                  </template>
                  分享
                </a-button>
                <a-button v-if="canEdit" @click="showEditModal">
                  <template #icon>
                    <EditOutlined/>
                  </template>
                  编辑
                </a-button>
                <a-popconfirm
                    v-if="canEdit"
                    cancel-text="取消"
                    ok-text="确定"
                    title="确定要删除这张图片吗？"
                    @confirm="handleDelete"
                >
                  <a-button danger>
                    <template #icon>
                      <DeleteOutlined/>
                    </template>
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </div>
          </div>

          <!-- 信息区 -->
          <div class="info-section">
            <a-card>
              <h1 class="picture-title">{{ picture.pictureName }}</h1>

              <!-- 作者信息 -->
              <div class="author-info">
                <a-avatar :size="48" :src="picture.user?.userAvatar">
                  {{ picture.user?.userName?.charAt(0) || 'U' }}
                </a-avatar>
                <div class="author-meta">
                  <div class="author-name">{{ picture.user?.userName || '匿名' }}</div>
                  <div class="upload-time">{{ formatDate(picture.createTime) }}</div>
                </div>
              </div>

              <!-- 图片简介 -->
              <div v-if="picture.introduction" class="picture-intro">
                <h3>简介</h3>
                <p>{{ picture.introduction }}</p>
              </div>

              <!-- 图片信息 -->
              <div class="picture-stats">
                <a-space :size="12" direction="vertical" style="width: 100%">
                  <div class="stat-item">
                    <EyeOutlined/>
                    <span>浏览 {{ picture.viewCount || 0 }} 次</span>
                  </div>
                  <div class="stat-item">
                    <DownloadOutlined/>
                    <span>下载 {{ picture.downloadCount || 0 }} 次</span>
                  </div>
                  <div class="stat-item">
                    <ShareAltOutlined/>
                    <span>分享 {{ picture.shareCount || 0 }} 次</span>
                  </div>
                </a-space>
              </div>

              <!-- 标签和分类 -->
              <div class="picture-meta">
                <div v-if="picture.category" class="meta-item">
                  <strong>分类：</strong>
                  <a-tag color="blue">{{ getCategoryLabel(picture.category) }}</a-tag>
                </div>
                <div v-if="picture.tags && picture.tags.length > 0" class="meta-item">
                  <strong>标签：</strong>
                  <a-space wrap>
                    <a-tag v-for="tag in picture.tags" :key="tag">{{ tag }}</a-tag>
                  </a-space>
                </div>
              </div>

              <!-- 图片属性 -->
              <div class="picture-properties">
                <h3>图片属性</h3>
                <a-descriptions :column="1" size="small">
                  <a-descriptions-item label="尺寸">
                    {{ picture.picWidth }} × {{ picture.picHeight }} 像素
                  </a-descriptions-item>
                  <a-descriptions-item label="格式">
                    {{ picture.picFormat?.toUpperCase() }}
                  </a-descriptions-item>
                  <a-descriptions-item label="大小">
                    {{ formatFileSize(picture.fileSize ?? 0) }}
                  </a-descriptions-item>
                  <a-descriptions-item label="审核状态">
                    <a-tag :color="getReviewStatusColor(picture.reviewStatus)">
                      {{ getReviewStatusText(picture.reviewStatus) }}
                    </a-tag>
                  </a-descriptions-item>
                </a-descriptions>
              </div>
            </a-card>
          </div>
        </div>
      </a-spin>

      <!-- 编辑对话框 -->
      <a-modal
          v-model:open="editModalVisible"
          :confirm-loading="updating"
          title="编辑图片信息"
          @ok="handleUpdate"
      >
        <a-form :model="editForm" layout="vertical">
          <a-form-item label="图片名称">
            <a-input v-model:value="editForm.pictureName" :maxlength="100"/>
          </a-form-item>
          <a-form-item label="图片简介">
            <a-textarea v-model:value="editForm.introduction" :maxlength="500" :rows="4"/>
          </a-form-item>
          <a-form-item label="所属空间">
            <a-select v-model:value="editForm.spaceId" allowClear placeholder="选择空间（可选）">
              <a-select-option :value="null">公共空间</a-select-option>
              <a-select-option
                  v-for="space in mySpaces"
                  :key="space.id"
                  :value="space.id"
              >
                {{ space.spaceName }}
              </a-select-option>
            </a-select>
            <div style="margin-top: 8px; font-size: 12px; color: #999;">
              修改所属空间将移动图片到新的空间
            </div>
          </a-form-item>
          <a-form-item label="分类">
            <a-select v-model:value="editForm.category" allowClear>
              <a-select-option
                  v-for="cat in PICTURE_CATEGORIES"
                  :key="cat.value"
                  :value="cat.value"
              >
                {{ cat.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="标签">
            <a-select v-model:value="editForm.tags" :max-tag-count="5" mode="tags"/>
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </main-layout>
</template>

<style lang="scss" scoped>
@use '@/assets/styles/variables.scss' as *;

.picture-detail-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 24px;
}

.detail-content {
  display: grid;
  grid-template-columns: 1fr 400px;
  gap: 24px;

  @media (max-width: 968px) {
    grid-template-columns: 1fr;
  }
}

.image-section {
  .image-wrapper {
    background: #000;
    border-radius: 12px;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 500px;

    :deep(.progressive-image) {
      max-width: 100%;
      max-height: 80vh;
      background: transparent;
      border-radius: 0;
      min-height: 0;

      img {
        max-width: 100%;
        max-height: 80vh;
      }
    }
  }

  .image-actions {
    margin-top: 16px;
    display: flex;
    justify-content: center;
  }
}

.info-section {
  .picture-title {
    font-size: 24px;
    font-weight: 600;
    margin-bottom: 24px;
  }

  .author-info {
    display: flex;
    gap: 12px;
    align-items: center;
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;

    .author-meta {
      flex: 1;

      .author-name {
        font-size: 16px;
        font-weight: 500;
      }

      .upload-time {
        font-size: 12px;
        color: #999;
        margin-top: 4px;
      }
    }
  }

  .picture-intro {
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;

    h3 {
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 8px;
    }

    p {
      color: #666;
      line-height: 1.6;
    }
  }

  .picture-stats {
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;

    .stat-item {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #666;
      font-size: 14px;
    }
  }

  .picture-meta {
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;

    .meta-item {
      margin-bottom: 12px;

      &:last-child {
        margin-bottom: 0;
      }

      strong {
        margin-right: 8px;
      }
    }
  }

  .picture-properties {
    padding: 16px 0;

    h3 {
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 12px;
    }
  }
}
</style>